package com.ivan.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.ivan.beans.Message;
import com.ivan.message.MessagesPool;
import com.ivan.util.DateUtil;

public class DispatchMessages extends HttpServlet{
	
	private static final long serialVersionUID = -7553026484825916208L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String toUser = request.getParameter("to");
		String content = request.getParameter("msg");
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if(user != null){
			String fromUser = user.getEmail();
			Message message = new Message();
			message.setFromUser(fromUser);
			message.setToUser(toUser);
			message.setMsgDate(DateUtil.now());
			message.setMessage(content);
			MessagesPool.pushMessage(message);
			System.out.println("Messag Put:" + message);
		} else {
			response.sendRedirect(userService.createLoginURL(request.getRequestURI()));
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	public boolean isEmpty(String val){
		return null == val || "".equals(val);
	}
	
}
